package handler

import (
	"2302a/chatroom/api/request"
	"2302a/chatroom/api/resp"
	"2302a/chatroom/consts"
	"2302a/chatroom/internal/dao"
	"2302a/chatroom/internal/model"
	"2302a/chatroom/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func UserRegister(c *gin.Context) {
	var req request.UserRegisterReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		resp.Error(c, 100002, "用户已存在", nil)
		return
	}
	release := model.Users{
		Nickname: req.Nickname,
		Mobile:   req.Mobile,
		Profile:  req.Profile,
		Password: pkg.GetEncryption(req.Password),
	}
	dao.Create(&release)
	if pkg.GetEncryption(req.Password) != pkg.GetEncryption(req.Confirm) {
		resp.Error(c, 100003, "两个密码不一致", nil)
		return
	}
	resp.Success(c, "注册成功", model.Users{
		Nickname: req.Nickname,
		Mobile:   req.Mobile,
		Profile:  req.Profile,
	})

}

func UserLogin(c *gin.Context) {
	var req request.UserLoginReq

	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "参数信息错误", err.Error())
		return
	}
	var user model.Users
	dao.GetOneByFields(&model.Users{Mobile: req.Mobile}, &user)
	if user.Id == 0 && pkg.GetEncryption(req.Password) != pkg.GetEncryption(req.Confirm) {
		resp.Error(c, 100002, "账号或者密码错误", nil)
		return
	}
	token := pkg.CreateAuthToken(user.Id, 24*time.Hour, consts.JWT_KEY)
	resp.Success(c, "登录成功", token)
}
